package com.example.auth.config;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.NotRoleException;
import com.example.auth.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理器
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理Sa-Token的NotLoginException异常
     */
    @ExceptionHandler(NotLoginException.class)
    public R<String> handleNotLoginException(NotLoginException e) {
        log.warn("未登录异常: {}", e.getMessage());
        return R.failed(R.ResultCode.UNAUTHORIZED.getCode(), "未登录或登录已过期");
    }

    /**
     * 处理Sa-Token的NotRoleException异常
     */
    @ExceptionHandler(NotRoleException.class)
    public R<String> handleNotRoleException(NotRoleException e) {
        log.warn("角色权限不足: {}", e.getMessage());
        return R.failed(R.ResultCode.FORBIDDEN.getCode(), "角色权限不足");
    }

    /**
     * 处理Sa-Token的NotPermissionException异常
     */
    @ExceptionHandler(NotPermissionException.class)
    public R<String> handleNotPermissionException(NotPermissionException e) {
        log.warn("权限不足: {}", e.getMessage());
        return R.failed(R.ResultCode.FORBIDDEN.getCode(), "权限不足");
    }

    /**
     * 处理参数校验异常
     */
    @ExceptionHandler(BindException.class)
    public R<String> handleBindException(BindException e) {
        BindingResult bindingResult = e.getBindingResult();
        StringBuilder sb = new StringBuilder();
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            sb.append(fieldError.getField()).append(": ").append(fieldError.getDefaultMessage()).append(", ");
        }
        String msg = sb.toString();
        if (sb.length() > 0) {
            msg = msg.substring(0, msg.length() - 2);
        }
        return R.failed(msg);
    }

    /**
     * 处理其他异常
     */
    @ExceptionHandler(Exception.class)
    public R<String> handleException(Exception e) {
        log.error("系统异常", e);
        return R.failed("系统异常，请联系管理员");
    }
} 